<?php
require_once(dirname(__FILE__).'/Abstract.php');

/**
 * MyAccount
 * 
 * Allows user to manage his an account, update his profile
 * 
 * @package Seowebd : Medic - Online
 * @author Seowebd
 * @copyright 2014
 * @version $Id$
 * @access public
 */
class MyAccount extends AbstractUserController 
{
	public function indexAction()
	{
		$this->profileAction();		
	}
	
	public function updateAction()
	{
		$d = array();
		$record = array();
				
		if ($this->session->userdata('id_user')){
    		$this->load->model('ORM/User/UserEntityORM');
    		$this->load->model('ORM/User/UserPatientORM');
    		//$user = $this->UserEntityORM->getByIdUser(/*$this->session->userdata('id_user')*/1);
    		$patient = $this->UserPatientORM->getByIdUser($this->session->userdata('id_user'));
    		$d['patient'] = $patient;
    		
    		if (empty($patient)){
    			$d['title'] = $this->l('Complete your account.');
    			$record1 = array(
    				'id_user' => $this->session->userdata('id_user'),
    			);
    		} else {
    			$d['title'] = $this->l('Update your account.');
    			$record1 = array(
    				'id_patient' => $patient->id_patient,
    			);
    		}

    		// On submit
        	if ($this->input->post('btn_submit') !== false){
                // Initialized the form validation
                $config = array(
                   array(
                         'field'   => 'birthday', 
                         'label'   => $this->l('Birthday'), 
                         'rules'   => 'trim|required|xss_clean'
                      ),
                   array(
                         'field'   => 'phone', 
                         'label'   => $this->l('Phone'), 
                         'rules'   => 'trim|required|xss_clean'
                      ),
                   array(
                         'field'   => 'profession', 
                         'label'   => $this->l('Profession'), 
                         'rules'   => 'trim|xss_clean'
                      ),
                   array(
                         'field'   => 'pobox', 
                         'label'   => $this->l('P.O.Box'), 
                         'rules'   => 'trim|xss_clean'
                      ),
                   array(
                         'field'   => 'town', 
                         'label'   => $this->l('Town'), 
                         'rules'   => 'trim|required|xss_clean'
                      ),
                   array(
                         'field'   => 'nb_serur_social', 
                         'label'   => $this->l('Social security number'), 
                         'rules'   => 'trim|xss_clean'
                      ),
                   array(
                         'field'   => 'address', 
                         'label'   => $this->l('Address'), 
                         'rules'   => 'trim|xss_clean'
                      ),
                );
                $this->form_validation->set_rules($config);
    			
    			if ($this->form_validation->run() == FALSE ){
    				$this->session->set_flashdata('errorMessage', $this->l('An error occured. Please check filled data and try again.'));
                } else {
                	// Initialize the new record
                    $record2 = array(
    					'birthday'     		=> $this->input->post('birthday'),
    					'phone'  			=> $this->input->post('phone'),
    					'profession' 		=> $this->input->post('profession'),
    					'pobox'  			=> $this->input->post('pobox'),
    					'town'    			=> $this->input->post('town'),
    					'nb_secur_social'   => $this->input->post('nb_secur_social'),
    					'address'    		=> $this->input->post('address'),
                        
                        // Automatic fill
    					'cmu'    => 0,                             // The cmu default value
    				);
    				
    				// Create the new account
                    if ($this->UserPatientORM->save(array_merge($record1,$record2))) {
                    	// Redirect to the account page
        				redirect('User/MyAccount/index');
                        die();
                    }
    			}
            }			
		} else {
			// Redirect to the sign in form
			redirect('User/AccountService/signIn');
            die();
		}
		
		$d['title_for_layout'] = $this->l('Manage your profile');
		$d['title'] = $this->l('Manage your profile');
        $d['menu'] = 'myaccount';
        $d['page_name'] = 'update';
		
		$this->load->view('Templates/Layouts/authLayout/header', $d);
        $this->load->view('User/MyAccount/Update', $d);
        $this->load->view('Templates/Layouts/authLayout/footer', $d);
	}


	public function profileAction()
	{
		$d = array();
		$d['title'] = $this->l('My Account');
		if ($this->session->userdata('id_user')){
			$this->load->model('ORM/User/UserEntityORM');
			$d['user'] = $this->UserEntityORM->getByIdUser($this->session->userdata('id_user'));
			
            $idRolePatient = $this->getConfig('idRolePatient');
            $idRoleDoctor  = $this->getConfig('idRoleDoctor');
            $idRoleAdmin   = $this->getConfig('idRoleAdmin');
            
            switch ($this->session->userdata('id_role')) {
				case $idRolePatient :
					$layout = 'Patient';
					$this->load->model('ORM/User/UserPatientORM');
					$d['patient'] = $this->UserPatientORM->getByIdUser($this->session->userdata('id_user'));
					break;
				case $idRoleDoctor :
					$layout = 'Doctor';
					$this->load->model('ORM/User/UserDoctorORM');
					$d['doctor'] = $this->UserDoctorORM->getByIdUser($this->session->userdata('id_user'));
					break;
				case $idRoleAdmin :
					$layout = 'Admin';
					break;
				default:
					$layout = 'Default';
					$this->load->model('ORM/User/UserPatientORM');
					$d['patient'] = $this->UserPatientORM->getByIdUser($this->session->userdata('id_user'));
					break;
			}
						
			$d['title_for_layout'] = $this->l('Manage your account.');
	        $d['menu'] = 'myaccount';
	        $d['page_name'] = 'profile';
			
	        
	        $this->load->view('Templates/Layouts/'.$layout.'/header', $d);
	        $this->load->view('User/MyAccount/Profile', $d);
	        $this->load->view('Templates/Layouts/'.$layout.'/footer', $d);
		} else {
			// Redirect to the sign in form
			redirect('User/AccountService/signIn');
            die();
		}
	}

	public function confirmationAction()
    {
		$d = array();
		$record = array();
        $this->load->model('ORM/User/UserEntityORM');
        
        if ($this->input->get_post('username') && $this->input->get_post('token')) {
            // Check if the account exist with the token
            $user = $this->UserEntityORM->getByUsernameAndToken($this->input->get_post('username'), $this->input->get_post('token'));
            if (!empty($user->id_user)) {
                if ($user->activated == 0) {
                    // Activation authorized
                    $record = array(
                        'id_user'       => $user->id_user, 
                        'activated'     => 1,
                        'last_activity' => @date('Y-m-d H:i:s') 
                        );
                    if ($this->UserEntityORM->save($record)) {
                        $this->session->set_flashdata('successMessage', $this->l('Your account was successfully confirmed. Contact a doctor on Medic Center for activating your account.'));
        				
                        // Send an alert to doctor
                        
                        // Go to sign in form
                        redirect('User/AccountService/signIn');
                        die();
                    } else {
                        $this->session->set_flashdata('errorMessage', $this->l('Confirmation of your account failed. Try again later or contact the support.'));
                    }
                } elseif ($user->activated == 1) {
                    $this->session->set_flashdata('successMessage', $this->l('Your account is already confirmed. Contact a doctor on Medic Center for activating your account.'));
    				redirect('User/AccountService/signIn');
                    die();
                } elseif ($user->activated == 2) {
                    $this->session->set_flashdata('successMessage', $this->l('Your account is already activated. You can sign in with you username and password.'));
    				redirect('User/AccountService/signIn');
                    die();
                }
            } else {
                // The account was not found
                $this->session->set_flashdata('errorMessage', $this->l('Confirmation of your account failed. Invalid token.'));
            }
            
        } elseif ($this->input->get_post('username')) {
            $user = $this->UserEntityORM->getByUsername($this->input->get_post('username'));
            if (!empty($user->id_user)) {
                $this->session->set_flashdata('errorMessage', $this->l('Confirmation of your account failed. Invalid token.'));
            } else {
                $this->session->set_flashdata('errorMessage', $this->l('Confirmation of your account failed. Invalid account.'));
            }
        } else {
            $this->session->set_flashdata('errorMessage', $this->l('Require the account and its token.'));
        }
        
        redirect('User/AccountService/signIn');
        die();
	}
    
}

